//
//  OilRechargeController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/6/11.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "OilRechargeController.h"

#import "OilChooseView.h"
#import "OilPayView.h"
#import "CreatStochasticOrderNumber.h"
#import "OrderPaymentController.h"
#import "LogInViewController.h"

#import "BindingOilCardTableViewController.h"

@interface OilRechargeController ()<OilChooseViewDelegate,didOilPayButtonDelegate>

{
    NSString *_payMoney;
    
    CGFloat _height;
}

@property(nonatomic,strong)XRCarouselView *XrCarouselView;

@property (nonatomic,strong)UITextField *phoneNumText;

@property (nonatomic,strong)UITextField *nameText;

@property(nonatomic,strong)UIView *OilInfoView;

@property (nonatomic,strong)NSArray *cycleUrlArray;

@property (nonatomic,strong)UILabel *label;

@property (nonatomic,strong)NSArray *chooseArray;

@property(nonatomic,strong)UIButton *btn;

@end

@implementation OilRechargeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = BACKGROUND_COLOR;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self addViews];
    _payMoney = @"100";
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"%s",__func__);
    
    if (!USERNAME) {
        return;
    }
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"username":USERNAME} AndMenthodName:@"api/User/info" completeBlock:^(id object) {
        
        NSDictionary *dict = [object objectForKey:@"data"];
        self.oilNumberString = [dict objectForKey:@"youka"];
        
        if (self.oilNumberString.length) {
            self.label.text = [NSString stringWithFormat:@"油卡:%@",self.oilNumberString];
        }
        
    }];
    
}

- (void)addViews
{
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"position":@"16"} AndMenthodName:@"/api/Ads/appAd" completeBlock:^(id object) {
        //        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            self.cycleUrlArray = [object objectForKey:@"data"];
            
            NSMutableArray *imageArr = [NSMutableArray array];
            for (NSDictionary *tempDict in self.cycleUrlArray) {
                NSString *str = tempDict[@"ad_code"];
                [imageArr addObject:str];
            }
            
            NSLog(@"%@",imageArr);
            
#warning  还有一些问题.轮播图重叠
            if (_XrCarouselView == nil || imageArr.count > 0) {
                _XrCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/6) imageArray:imageArr];;
                self.XrCarouselView.time = 2;
                [self.view addSubview:self.XrCarouselView];
                
            }
        }
    }];
    
    //适配
    CGFloat margin= 5;
    CGFloat inputCount;
    CGFloat chooseCount;
    CGFloat height;
    if (iPhone5) {
        inputCount = 10;
        chooseCount = 7;
        height = 25;
    }else if (iPhone6) {
        inputCount = 9;
        chooseCount = 6;
        height = 35;
    } else {
        inputCount = 9;
        chooseCount = 6;
        height = 40;
    }
    
    _height = height;
    
    [self addOilInfoView:margin height:height];
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"type":@"2",@"client_type":@"2"} AndMenthodName:@"/api/card/index" completeBlock:^(id object) {
        self.chooseArray = [object objectForKey:@"data"];
        _payMoney = self.chooseArray.firstObject[@"dynamic_price"];
        
        OilChooseView *chooseView = [[OilChooseView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(self.OilInfoView.frame)+margin, WIDTH, HEIGHT/chooseCount)];
        [self.view addSubview:chooseView];
        chooseView.chooseArray = self.chooseArray;
        chooseView.delegate = self;
        
        
        OilPayView *payView = [[OilPayView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(chooseView.frame), WIDTH,HEIGHT-self.XrCarouselView.Height-chooseView.Height-self.OilInfoView.Height-margin*2)];
        payView.delegate = self;
        [self.view addSubview:payView];
        self.btn = payView.payBtn;
    }];
    
    
}

#pragma mark >>>>>>>>>>OilChooseView代理
- (void)OilChooseViewDidClick:(UIButton *)button
{
    //    NSLog(@"%ld",button.tag);
    [self resignResponderTextField];
    
//    if (button.tag == 100) {
//        NSLog(@"0");
//        _payMoney = @"100";
//    }else {
//        NSLog(@"1");
//        _payMoney = @"500";
//    }
    _payMoney = [self.chooseArray[button.tag - 100] objectForKey:@"dynamic_price"];
}

- (UIView *)addOilInfoView:(CGFloat)margin height:(CGFloat)height
{
    UIView *OilInfoView = [[UIView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(self.XrCarouselView.frame) + margin, WIDTH, HEIGHT/5.3)];
    self.OilInfoView = OilInfoView;
    [self.view addSubview:OilInfoView];
    OilInfoView.backgroundColor = [UIColor whiteColor];
    
    UILabel *oilLabel = [[UILabel alloc] initWithFrame:CGRectMake(15,5,WIDTH-30,25)];
    [OilInfoView addSubview:oilLabel];
    if (self.oilNumberString.length) {
        oilLabel.text = [NSString stringWithFormat:@"油卡:%@",self.oilNumberString];
    } else {
        oilLabel.text = @"暂无油卡信息,请绑定油卡号";
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(15,5,WIDTH-30,25)];
        [OilInfoView addSubview:btn];
        [btn addTarget:self action:@selector(pushBindingOilCardTableViewController) forControlEvents:UIControlEventTouchUpInside];
        
    }
    oilLabel.font = [UIFont systemFontOfSize:15];
    oilLabel.textColor = [UIColor grayColor];
    self.label = oilLabel;
    
    UITextField * phoneNumText= [[UITextField alloc] initWithFrame:CGRectMake(15,CGRectGetMaxY(oilLabel.frame)+10,oilLabel.width,height)];
    phoneNumText.placeholder = @"请输入手机号码";
    [OilInfoView addSubview:phoneNumText];
    phoneNumText.borderStyle = UITextBorderStyleRoundedRect;
    phoneNumText.font = [UIFont systemFontOfSize:14];
    phoneNumText.textColor = [UIColor blackColor];
    phoneNumText.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneNumText = phoneNumText;
    
    UITextField * nameText= [[UITextField alloc] initWithFrame:CGRectMake(15,CGRectGetMaxY(phoneNumText.frame)+8,oilLabel.width,height)];
    nameText.placeholder = @"持卡人姓名";
    [OilInfoView addSubview:nameText];
    nameText.borderStyle = UITextBorderStyleRoundedRect;
    nameText.font = [UIFont systemFontOfSize:14];
    nameText.textColor = [UIColor blackColor];
    self.nameText = nameText;
    
    return OilInfoView;
}

- (void)pushBindingOilCardTableViewController
{
    BindingOilCardTableViewController *BindingOilCardVC = [[BindingOilCardTableViewController alloc] init];
    [self.navigationController pushForm:self.navigationController pushToAndHidden:BindingOilCardVC];
}

- (void)didOilPayButtonToPush {
    
    if (!USERNAME) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您尚未登录用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LogInViewController *accountVC = [[LogInViewController alloc] init];
            accountVC.JudgeLogInBack = NO;
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:accountVC];
            [self presentViewController:nav animated:YES completion:nil];
        }];
        [alert addAction:SettingAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    if (!self.phoneNumText.text.length || !self.nameText.text.length) {
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"请输入正确的账号信息" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
        return;
    }
    
    [self.btn setBackgroundColor:[UIColor lightGrayColor]];
    [self.btn setEnabled:false];
    
//    http://www.dev.ylgw8.com/api/Order/createOrderId?username=18000000000&business_tpye=oil_card&rcMoney=100&phoneNo=18620614920&gasCardName=郑州三
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary *params = @{
                                 @"username":USERNAME,
                                 @"business_type":@"oil_card",
                                 @"money":_payMoney,
                                 @"phone":self.phoneNumText.text,
                                 @"gasCardName":self.nameText.text
                                 };
        
        NSLog(@"%@",params);
        
//        http://www.dev.ylgw8.com/api/Order/createOrderId/username/18620614920/business_tpye/oil_card/money/100/phone/18620614920/gasCardName/中中
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Order/createOrderId" completeBlock:^(id object) {
            
            NSLog(@"%@",object);
            
            if (JudgeBackDataCode) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSString *orderNumber = [object objectForKey:@"data"];
                    
                    OrderPaymentController *OrderPaymentVC = [[OrderPaymentController alloc] init];
                    
                    OrderPaymentVC.OrderString = orderNumber;
                    OrderPaymentVC.OrderTitleString = @"油卡充值";
                    OrderPaymentVC.OrderDescribeInfo = self.oilNumberString;
                    OrderPaymentVC.OrderMonryString = _payMoney;
                    OrderPaymentVC.judgeOilRecharge = YES;
                    OrderPaymentVC.orderType = @"2";
                    [self.navigationController pushForm:self.navigationController pushToAndHidden:OrderPaymentVC];
                    
                });
            } else if ([[NSString stringWithFormat:@"%@",object[@"code"]] isEqualToString:@"-9000"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSDictionary *MessageDict = [object objectForKey:@"message"];
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:MessageDict[@"view"] message:nil preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        MyAccountTableViewController *accountVC = [[MyAccountTableViewController alloc] init];
                        [self.navigationController pushForm:self.navigationController pushToAndHidden:accountVC];
                    }];
                    [alert addAction:SettingAction];
                    
                    
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alert addAction:cancelAction];
                    
                    [self presentViewController:alert animated:YES completion:nil];
                    
                });
            }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
//                    NSDictionary *MessageDict = [object objectForKey:@"message"];
                    
                    MBProgressHUD *hud = [MBProgressHUD showMessage:@"订单创建失败" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                    [self.view addSubview:hud];
                    
                });
            }
            
            [self.btn setBackgroundColor:DEFAULT_COLOR];
            [self.btn setEnabled:true];
            
        }];
        
//        [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:params AndMenthodName:@"/api/Order/createOrderId" completeBlock:^(id object) {
//            
//           
//            
//        }];
        
    });
    
    
    
}

#pragma mark>>>>>>>>>>懒加载轮播
- (XRCarouselView *)XrCarouselView
{
    if (!_XrCarouselView) {
        NSMutableArray *imageArr = [NSMutableArray array];
        for (NSDictionary *tempDict in self.cycleUrlArray) {
            NSString *str = tempDict[@"ad_code"];
            [imageArr addObject:str];
        }
        
#warning  还有一些问题.轮播图重叠
        if (_XrCarouselView == nil || imageArr.count > 0) {
            _XrCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/6) imageArray:imageArr];
            self.XrCarouselView.delegate = self;
            self.XrCarouselView.time = 2;
            [self.view addSubview:self.XrCarouselView];
        }
    }
    return _XrCarouselView;
}

- (NSArray *)cycleUrlArray {
    if (!_cycleUrlArray) {
        _cycleUrlArray = [NSArray array];
    }
    return _cycleUrlArray;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self resignResponderTextField];
}

- (void)resignResponderTextField {
    [self.phoneNumText resignFirstResponder];
    [self.nameText resignFirstResponder];
}

- (NSArray *)chooseArray {
    if (!_chooseArray) {
        _chooseArray = [NSArray array];
    }
    return _chooseArray;
}

@end
